<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item :label="$t('equipment.channelName')" prop="name">
        <el-input
            v-model="queryParams.name"
            :placeholder="$t('equipment.channelNameInput')"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('equipment.channelType')" prop="type">
        <el-select v-model="queryParams.type" :placeholder="$t('equipment.channelTypeInput')" clearable size="small">
          <el-option :label="$t('equipment.channelType1')" value="0"/>
          <el-option :label="$t('equipment.channelType2')" value="1"/>
          <el-option :label="$t('equipment.channelType3')" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('equipment.status')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('equipment.statusSelect')" clearable size="small">
          <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('elButton.establishTime')">
        <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('elButton.startTime')"
            :end-placeholder="$t('elButton.endTime')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{
            $t('elButton.search')
          }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('elButton.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPerm="['scheduling_add']"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >{{ $t('elButton.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPerm="['scheduling_edit']"
            type="success"
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleEdit"
        >{{ $t('elButton.change') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPerm="['scheduling_del']"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDel"
        >{{ $t('elButton.delete') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPerm="['scheduling_export']"
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
        >{{ $t('elButton.export') }}
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-button-group>
          <el-button @click="closeList('dayGridMonth')">{{ $t('elButton.month') }}</el-button>
          <el-button @click="closeList('timeGridWeek')">{{ $t('elButton.week') }}</el-button>
          <el-button @click="closeList('timeGridDay')">{{ $t('elButton.day') }}</el-button>
        </el-button-group>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="schedulingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column :label="$t('equipment.number')" align="center" prop="id" width="55"/>
      <el-table-column :label="$t('equipment.channelName')" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column :label="$t('equipment.channelType')" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == '0'" type="info">{{ $t('equipment.channelType1') }}</el-tag>
          <el-tag v-if="scope.row.type == '1'">{{ $t('equipment.channelType2') }}</el-tag>
          <el-tag v-if="scope.row.type == '2'" type="danger">{{ $t('equipment.channelType3') }}</el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column label="发布方式" align="center" prop="way" />-->
      <el-table-column :label="$t('equipment.channelMode')" align="center" prop="playMode">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.playMode == '0'" type="info">{{ $t('equipment.channelMode1') }}</el-tag>
          <el-tag v-if="scope.row.playMode == '1'" type="success">{{ $t('equipment.channelMode2') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.channelPlayWeek')" align="center" prop="playWeeks"/>
      <el-table-column :label="$t('equipment.channelPlayDate')" align="center" prop="startDate"
                       :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{
              `${parseTime(scope.row.startDate, '{y}-{m}-{d}')}` + $t('untils') + `${parseTime(scope.row.stopDate, '{y}-{m}-{d}')}`
            }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.channelPlayTime')" align="center" prop="startTime"
                       :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ `${scope.row.startTime}` + $t('untils') + `${scope.row.stopTime}` }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.downLoadTime')" align="center" prop="dloadTime"
                       :show-overflow-tooltip="true" width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dloadTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('program.status')" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column :label="$t('elButton.establishTime')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.control')" align="center" class-name="small-padding fixed-width"
                       width="180"
      >
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.status === '0'"
              v-hasPerm="['scheduling_audit']"
              size="mini"
              type="text"
              icon="el-icon-circle-check"
              @click="handleAudit(scope.row)"
          >{{ $t('elButton.examine') }}
          </el-button>
          <el-button
              v-hasPerm="['scheduling_edit']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
          >{{ $t('elButton.change') }}
          </el-button>
          <el-button
              v-hasPerm="['scheduling_del']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.row)"
          >{{ $t('elButton.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getList"
    />

    <add
        v-model="open"
        :title.sync="title"
        :basic-info.sync="basicInfo"
        :selected-device-list.sync="selectedDeviceList"
        :selected-play-program-list.sync="selectedPlayProgramList"
        :click-btn="clickBtn"
        @save="handleSave"
    />

    <!--审核页面-->
    <audit
        :obj="auditObj"
        :visible.sync="auditVisible"
        :audit-title="$t('program.channelShenhe')"
        audit-type="scheduling"
        @refresh="getList"
    >
      <h3>{{ $t('program.channelShenheTitle') }}</h3>
    </audit>
  </div>
</template>

<script>
import AuditMixin from '@/mixins/audit/index.js'
import {
  listScheduling,
  getScheduling,
  delScheduling,
  addScheduling,
  editScheduling,
  exportScheduling
} from '@/api/ips/scheduling'
import Add from './add/index.vue'

export default {
  name: 'NewScheduling',
  components: { Add },
  mixins: [AuditMixin],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 频道表格数据
      schedulingList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态字典
      statusOptions: [], // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        type: undefined,
        playMode: undefined,
        // devices: undefined,
        programs: undefined,
        status: undefined,
        createTime: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 新增/编辑的基本信息
      basicInfo: {
        name: '',
        type: '1',
        startDateTime: '',
        endDateTime: '',
        playWeeks: [],
        playMode: '',
        way: '',
        delData: ''
      },
      // 新增/编辑选择的节目信息
      selectedPlayProgramList: [],
      // 新增/编辑选择的设备信息
      selectedDeviceList: [],
      // 是新增(ADD) 还是编辑(EDIT)
      clickBtn: null
    }
  },
  created() {
    this.getList()
    this.getDicts('check_status').then(response => {
      this.statusOptions = response.data
    })

    if (this.$route.query.handleAdd) {
      setTimeout(() => {
        this.handleAdd()
      }, 1000)
    }
  },
  methods: {
    /** 查询频道列表 */
    getList() {
      this.loading = true
      listScheduling(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.schedulingList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        type: undefined,
        way: undefined,
        playMode: undefined,
        playWeeks: undefined,
        startDateTime: undefined,
        endDateTime: undefined,
        startDate: undefined,
        stopDate: undefined,
        startTime: undefined,
        stopTime: undefined,
        // devices: undefined,
        programs: undefined,
        dloadTime: undefined,
        status: '0',
        delData: ''
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.clickBtn = 'ADD'
      // this.reset()
      this.open = true
      this.title = this.$t('equipment.addChanel')
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.clickBtn = 'EDIT'
      // this.reset()
      const id = row.id || this.ids
      getScheduling(id).then(response => {
        this.basicInfo = response.data
        this.basicInfo.playWeeks = this.basicInfo.playWeeks.split(',')
        if (this.basicInfo.programs) {
          this.selectedPlayProgramList = JSON.parse(this.basicInfo.programs)
        }
        // if (this.basicInfo.devices) {
        //   this.selectedDeviceList = JSON.parse(this.basicInfo.devices)
        // }
        const dateTemp = []
        dateTemp.push(this.basicInfo.startDate)
        dateTemp.push(this.basicInfo.stopDate)
        this.$set(this.basicInfo, 'startDateTime', dateTemp)
        const timeTemp = []
        timeTemp.push(this.basicInfo.startTime)
        timeTemp.push(this.basicInfo.stopTime)
        this.$set(this.basicInfo, 'endDateTime', timeTemp)
        if (this.compareTime(this.basicInfo.dloadTime)) {
          this.$set(this.basicInfo, 'nowDown', true)
        } else {
          this.$set(this.basicInfo, 'nowDown', false)
        }
        this.open = true
        this.title = '修改频道'
      })
    },
    compareTime(time) {
      var date1 = new Date()
      var date2 = new Date(time)
      if (date1.getTime() > date2.getTime()) {
        return true
      } else {
        return false
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            editScheduling(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('loginLog.changeSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addScheduling(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess(this.$t('addSuccess'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id || this.ids
      this.$confirm(this.$t('equipment.deleteChanel') + ids + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delScheduling(ids)
      }).then(() => {
        this.getList()
        console.log(this.$parent)
        this.$emit('getTreeList')
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('equipment.exportChannel'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return exportScheduling(queryParams)
      }).then(response => {
        this.download(response.data)
      }).catch(function() {
      })
    },
    handleSave() {
      const fun = this.basicInfo.id ? editScheduling : addScheduling
      if (this.basicInfo.type === '0') {
        this.basicInfo.startDate = '1999-12-31'
        this.basicInfo.stopDate = '2999-12-31'
        this.basicInfo.startTime = this.basicInfo.endDateTime[0]
        this.basicInfo.stopTime = this.basicInfo.endDateTime[1]
      } else {
        this.basicInfo.startDate = this.basicInfo.startDateTime[0]
        this.basicInfo.stopDate = this.basicInfo.startDateTime[1]
        this.basicInfo.startTime = this.basicInfo.endDateTime[0]
        this.basicInfo.stopTime = this.basicInfo.endDateTime[1]
      }
      this.basicInfo.playWeeks = this.basicInfo.playWeeks.join(',')
      if (this.selectedPlayProgramList.length > 0) {
        const tmp = []
        this.selectedPlayProgramList.forEach(element => {
          tmp.push(element.id)
        })
        this.basicInfo.programId = tmp.toString()
        this.basicInfo.programs = JSON.stringify(this.selectedPlayProgramList)
      } else {
        this.basicInfo.programs = ''
        this.basicInfo.programId = ''
      }
      // if (this.selectedDeviceList.length > 0) {
      //   this.basicInfo.devices = JSON.stringify(this.selectedDeviceList) // .map(it => it.id).join(',')
      // } else {
      //   this.basicInfo.devices = ''
      // }
      if (this.basicInfo.nowDown) {
        this.basicInfo.isTiming = '0'
        this.basicInfo.dloadTime = this.parseTime(new Date())
      } else {
        this.basicInfo.isTiming = '1'
      }
      fun(this.basicInfo)
          .then(_ => {
            this.$message({
              message: this.$t('saveSuccess'),
              type: 'success',
              showClose: true
            })
            this.open = false
            this.$emit('getTreeList')
            this.getList()
          })
          .catch(_ => {
          })
    },

    closeList(data) {
      this.$emit('open', data)
    }
  }
}
</script>

<style scoped>
.top-right-btn .el-button {
  background-color: #2c3e50;
  color: #fff;
  margin-left: 0;
}
</style>
